/**
	云主机
 */
package zstack

import (
	"bc/util"
	"fmt"
	"strconv"
)

type vm struct {

}
/**
	创建云主机
	body{
	  "params": {
		"name": "vm1",
		"instanceOfferingUuid": "ae97ced44efc3314b8f7798972b4ba1a",
		"imageUuid": "da119f7906513eccabf271991c35a65e",
		"l3NetworkUuids": [
		  "cc0e4c5e77df3af68e59668e7f9e06c5"
		],
		"dataDiskOfferingUuids": [
		  "19d22d051b063d379a2816daaf431838",
		  "905d94a6abb5398fa1995f6398e3f6fc"
		],
		"clusterUuid": "a0468dc645223f67bd0f2ab95276bbae",
		"description": "this is a vm",
		"strategy": "InstantStart"
	  },
	  "systemTags": [],
	  "userTags": []
	}
 */
func (t *vm)Create(body string,sn_id int,uid int) (string,error) {

	oauth,err := Oauth()
	if err != nil{
		panic(err)
	}
	id := strconv.Itoa(sn_id)
	userId := strconv.Itoa(uid)
	url := util.Config.Zstack.ApiUrl + "v1/vm-instances"
	header := make(map[string]string)
	header["Content-Type"] = "application/json;charset=UTF-8"
	header["Authorization"] = "OAuth " + oauth
	header["X-Web-Hook"] = util.Config.Zstack.WebHook + "create_vm_call_back?sn_id=" + id + "&uid=" + userId

	str,err := util.Curl.Header(header).Url(url).Body(body).POST()
	return str,err

}
/**
	删除云主机
 */
func (t *vm)Delete(uuid string,del_mode string)(string,error){

	oauth,err := Oauth()
	if err != nil{
		panic(err)
	}
	url := util.Config.Zstack.ApiUrl + "v1/vm-instances/%s?deleteMode=%s"
	url = fmt.Sprintf(url,uuid,del_mode)
	header := map[string]string{}
	header["Content-Type"] = "application/json;charset=UTF-8"
	header["Authorization"] = "OAuth " + oauth
	str,err := util.Curl.Header(header).Url(url).DELETE()
	return str,err

}
/**
	恢复已删除的云主机
	恢复一个处于Destroyed状态的云主机。恢复后云主机处于Stopped状态并且没有IP地址
 */
func (t *vm)RecoverVm(uuid string) (string,error){

	oauth,err := Oauth()
	if err != nil{
		panic(err)
	}
	url := util.Config.Zstack.ApiUrl + "v1/vm-instances/%s/actions"
	url = fmt.Sprintf(url,uuid)
	header := map[string]string{}
	header["Content-Type"] = "application/json;charset=UTF-8"
	header["Authorization"] = "OAuth " + oauth

	str,err := util.Curl.Header(header).Url(url).PUT()
	return str,err

}
/**
	彻底删除一个处于Destroyed状态的云主机。
	该操作会从数据库里面删除云主机并在主存储上删除该云主机的根云盘。该操作一旦执行就不可恢复
 */
func (t *vm)ExpungeVm(uuid string) (string,error){

	oauth,err := Oauth()
	if err != nil{
		panic(err)
	}
	url := util.Config.Zstack.ApiUrl + "v1/vm-instances/%s/actions"
	url = fmt.Sprintf(url,uuid)
	header := map[string]string{}
	header["Content-Type"] = "application/json;charset=UTF-8"
	header["Authorization"] = "OAuth " + oauth

	str,err := util.Curl.Header(header).Url(url).PUT()
	return str,err

}

var VM = &vm{}
